#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       makesite.py
#       
#       Copyright 2011 www.soycode.com
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 3 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

"""
Create HTML files and folder hierarchy for arcade web site.
www.soycode.com
"""

# standard
import cgi
import codecs
import os
import re
import time
# enable for debugging
#import cgitb
#cgitb.enable()
# installed
from mochi import autopost

PUBLISHER_ID = 'ENTER_YOUR_PUBLISHER_ID_HERE'


def StartBasePage(page, title, description=''):
  """Write base opening tags for a webpage."""
  page.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"' +
             '"http://www.w3.org/TR/html4/loose.dtd">\n')
  page.write('<html>\n')
  page.write('<head>\n<title>proles.net flash game arcade - ' + title +
             '</title>\n')
  page.write('<meta http-equiv="Content-Type" content="text/html;' +
             'charset=utf-8">\n')
  page.write('<meta name="description" content="' + description + '">\n')
  page.write('<link rel="stylesheet" type="text/css" href="/style.css">')
  page.write('</link>\n')
  page.write('<script type="text/javascript" src="/boxover.js"></script>\n')
  page.write('</head>\n<body>\n')


def EndBasePage(page):
  """Write base closing tags for a webpage."""
  page.write('<center><p class="timestamp">Last updated: ' + time.asctime())
  page.write('</p></center>\n</body>\n</html>')


def MakeGame(gameinfo):
  """Make the inner HTML for an individual game webpage."""
  game = str(gameinfo.data['slug'])
  gameswf = re.sub('.*/', '', gameinfo.get_swf_name())
  gamewidth = str(gameinfo.data['width'])
  gameheight = str(gameinfo.data['height'])
  gamepage = codecs.open('./games/' + game + '/index.html', 'w', 'utf-8')
  StartBasePage(gamepage, gameinfo.data['name'], gameinfo.data['description'])
  gamepage.write('<center><h1>' + gameinfo.data['name'] + '</h1>\n')
  gamepage.write('\n<object width="' + gamewidth + '" height="' +
                  gameheight + '">\n')
  gamepage.write('<param name="movie" value="' + gameswf + '">\n')
  gamepage.write('<embed src="' + gameswf + '" width="' + gamewidth +
                  '" height="' + gameheight + '">')
  gamepage.write('</embed>\n</object>\n')
  gamepage.write('<p class="instructions">Instructions: ' +
                 gameinfo.data['instructions'] + '</p>\n')
# todo: either break out controls or don't worry about them
#  gamepage.write('\n<p>Controls: ' + gameinfo.data['control_scheme'] + '</p>')
  gamepage.write('<p><a href="/">Back to the proles.net flash game arcade')
  gamepage.write('</a></p>\n')
  gamepage.write ('<p class="timestamp">Tags: ')
  for tag in gameinfo.data['tags']:
    gamepage.write(tag)
    if tag != gameinfo.data['tags'][len(gameinfo.data['tags']) - 1]:
      gamepage.write(', ')
  gamepage.write('</p></center>\n')
  EndBasePage(gamepage)
  gamepage.close()


def MakeIndex():
  """Make the inner HTML and sitemap for the main game index page."""
  games = os.listdir('./games')
  games.sort()
  sitemap = codecs.open('sitemap.xml', 'w', 'utf-8')
  sitemap.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  sitemap.write('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
  sitemap.write('\t<url>\n\t\t<loc>http://proles.net/</loc>\n\t</url>\n')
  index = codecs.open('index.html', 'w', 'utf-8')
  StartBasePage(index, 'just the games', 'A flash web arcade with handpicked' +
                ' games, only publisher-required ads, and no other nonsense.')
  index.write('<center>\n')
  index.write('<h1>proles.net flash game arcade - just the games</h1>\n')
  index.write('<div class="games">\n')
  for game in games:
    gameinfo = autopost.get_game('./games', slug=game)
    sitemap.write('\t<url>\n\t\t<loc>http://proles.net/games/' + game +
                  '/</loc>\n\t</url>\n')
    thumbnail = re.sub('.*/', '', gameinfo.data['thumbnail_url'] + '" ')
    index.write('<a href="./games/' + game + '">\n')
    index.write('<img src="./games/' + game + '/' + thumbnail)
    index.write('class="thumbnail" ')
    # boxover stuff
    index.write('title="header=[' + gameinfo.data['name'] + '] body=[' +
                gameinfo.data['description'] + ']">\n')
    index.write('</a>\n')
  index.write('</div>\n')
  sitemap.write('</urlset>')
  sitemap.close()
  EndBasePage(index)
  index.close()


def UpdateSite(game_tags):
  """(Re)create index and specified game pages."""
  for game_tag in game_tags:
    gameinfo = autopost.get_game('./games', game_tag=game_tag)
    MakeGame(gameinfo)
  MakeIndex()


def CheckUpdate(game):
  """Check which games on site have newer versions at Mochi."""
  gameinfo = autopost.get_game('./games', slug=game)
  # todo: patch this functionality into python mochi, commit?
  newurl = str(autopost.__MOCHI_FEED + PUBLISHER_ID + '/' +
           gameinfo.data['game_tag'] + autopost.__MOCHI_FEED_FORMAT_SUFFIX)
  response = autopost.urllib2.urlopen(newurl)
  newgameinfo = autopost.json.load(response)['games'][0]
  # todo: seems like these updateds are always different for some stupid reason
  # hacky: this way of date/string comparison may not always work...
  if newgameinfo['updated'] > gameinfo.data['updated']:
    autopost.fetch_game(PUBLISHER_ID, newgameinfo['game_tag'], './games')
    print '%s updated<br>' % newgameinfo['name']
    return newgameinfo['game_tag']


def main():
  print 'Content-type: text/html\n'
  games = os.listdir('./games')
  game_tags = []
  for game in games:
    updated = CheckUpdate(game)
    if updated:
      game_tags.append(updated)
  UpdateSite(game_tags)
  print 'Update successful: %i new games' % len(game_tags)


if __name__ == "__main__":
  main()

